package previous.Test_0220;

import java.util.*;

/**
 * Created with Intellij IDEA
 * Description:
 * User: 星辰
 */
public class Solution {
    //判断是否为字符重排
    public boolean CheckPermutation1(String s1, String s2) {
        HashMap<Character,Integer> hashMap=new HashMap<Character,Integer>();
        if(s1.length()!=s2.length()){
            return false;
        }
        for (int i = 0; i < s1.length(); i++) {
            hashMap.put(s1.charAt(i),hashMap.getOrDefault(s1.charAt(i),0)+1);
        }
        for (int i = 0; i < s2.length(); i++) {
            char x=s2.charAt(i);
            if(hashMap.containsKey(x)){
                int count=hashMap.get(x);
                if(count==1){
                    hashMap.remove(x);
                }else{
                    hashMap.put(x,count-1);
                }
            }else{
                return false;
            }
        }
        return true;
    }
    public boolean CheckPermutation(String s1, String s2) {
        if(s1.length()!=s2.length()){
            return false;
        }
          int[] hash1=new int[26];
          int[] hash2=new int[26];
        for (int i = 0; i <s1.length() ; i++) {
            hash1[s1.charAt(i)-'a']+=1;
        }
        for (int i = 0; i <s1.length() ; i++) {
            hash2[s2.charAt(i)-'a']--;
            if( hash2[s2.charAt(i)-'a']--<0) return false;
        }
        return true;
    }
    //存在重复元素
    public boolean containsDuplicate(int[] nums) {
        HashMap<Integer,Integer> hash=new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(hash.containsKey(nums[i])){
                return true;
            }else{
                hash.put(nums[i],i);
            }
        }
        return false;
    }
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer,Integer> hash=new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(hash.containsKey(nums[i])){
                int x=hash.get(nums[i]);
                int t=i-x;
                if(t<=k){
                    return true;
                }else{
                    hash.put(nums[i],i);
                }
            }else{
                hash.put(nums[i],i);
            }
        }
        return false;
    }
    //字母异位词分组位
    public List<List<String>> groupAnagrams(String[] strs) {

           HashMap<String,List<String>> hash=new HashMap<>();
        for (String s:strs) {
            char[] t=s.toCharArray();
            //排序
            Arrays.sort(t);
            String k=new String(t);
            if(!hash.containsKey(k)){
                hash.put(s,new ArrayList<>());
            }
            hash.get(k).add(s);
        }
        return new ArrayList<>(hash.values());
    }
}
